require("dotenv").config();
const { pool } = require("../config/db");
const jwt = require("jsonwebtoken");
const { ethers } = require("ethers");

// 测试数据库连接
async function testDbConnection() {
  try {
    const [result] = await pool.query("SELECT 1 as test");
    console.log("数据库连接成功:", result);
    return true;
  } catch (error) {
    console.error("数据库连接失败:", error);
    return false;
  }
}

// 测试JWT令牌生成和验证
async function testJwtToken() {
  try {
    const testUser = { id: 999, username: "test_user" };
    const token = jwt.sign(testUser, process.env.JWT_SECRET, {
      expiresIn: "1h",
    });
    console.log("JWT令牌生成成功:", token);

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    console.log("JWT令牌验证成功:", decoded);
    return true;
  } catch (error) {
    console.error("JWT令牌测试失败:", error);
    return false;
  }
}

// 测试钱包地址验证
async function testWalletAddressValidation() {
  try {
    const validAddress = "0x71C7656EC7ab88b098defB751B7401B5f6d8976F";
    const invalidAddress = "0xinvalid";

    console.log("有效地址验证结果:", ethers.utils.isAddress(validAddress));
    console.log("无效地址验证结果:", ethers.utils.isAddress(invalidAddress));
    return true;
  } catch (error) {
    console.error("钱包地址验证测试失败:", error);
    return false;
  }
}

// 测试钱包绑定功能
async function testWalletBind() {
  try {
    // 创建测试用户
    const testUsername = `test_user_${Date.now()}`;
    const [userResult] = await pool.query(
      "INSERT INTO users (username, password) VALUES (?, ?)",
      [testUsername, "test_password"]
    );
    const userId = userResult.insertId;
    console.log(`创建测试用户成功, ID: ${userId}`);

    // 绑定钱包地址
    const testWalletAddress = "0x71C7656EC7ab88b098defB751B7401B5f6d8976F";
    await pool.query("UPDATE users SET wallet_address = ? WHERE id = ?", [
      testWalletAddress,
      userId,
    ]);
    console.log(`绑定钱包地址成功: ${testWalletAddress}`);

    // 验证绑定结果
    const [users] = await pool.query(
      "SELECT wallet_address FROM users WHERE id = ?",
      [userId]
    );

    if (users.length > 0 && users[0].wallet_address === testWalletAddress) {
      console.log("钱包绑定验证成功");

      // 清理测试数据
      await pool.query("DELETE FROM users WHERE id = ?", [userId]);
      console.log("清理测试数据成功");

      return true;
    } else {
      console.error("钱包绑定验证失败");
      return false;
    }
  } catch (error) {
    console.error("钱包绑定测试失败:", error);
    return false;
  }
}

// 运行所有测试
async function runAllTests() {
  console.log("===== 开始测试 =====");

  const dbConnected = await testDbConnection();
  if (!dbConnected) {
    console.error("数据库连接测试失败，终止后续测试");
    return;
  }

  await testJwtToken();
  await testWalletAddressValidation();
  await testWalletBind();

  console.log("===== 测试完成 =====");

  // 关闭数据库连接
  pool.end();
}

runAllTests();
